//
//  PickNum7xcListViewController.m
//  PlayBall
//
//  Created by Sun Fanglei on 13-4-8.
//
//

#import "JddPickNum7xcListViewController.h"
#import "JddViewControllerManager.h"

@interface JddPickNum7xcListViewController ()

@end

@implementation JddPickNum7xcListViewController

@synthesize lotNumListTable;
@synthesize mutipleTextField;
@synthesize countLabel;
@synthesize moneyLabel;
@synthesize mutiLabel;
@synthesize buyButton;
@synthesize bgScrollView;

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddPickNum7xcListViewController);

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789\n"]invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    BOOL canChange = [string isEqualToString:filtered];
    
    if (!canChange) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"倍数只能输入数字"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        return NO;
    }
    if ([string length] + range.location>3) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"倍数不能大于999"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        return NO;
    }
    
    if ([textField.text length] == 0) {
        if([string isEqualToString:@"0"]){
            return NO;
        }else {
            moneyLabel.text = [NSString stringWithFormat:@"%d彩豆", noteAmount * [[textField.text stringByReplacingCharactersInRange:range withString:string] intValue] * 2];
            return YES;
        }
    }
    if (range.location >= 3){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"倍数不能大于999"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        return NO;
    }else {
        moneyLabel.text = [NSString stringWithFormat:@"%d彩豆", noteAmount * [[textField.text stringByReplacingCharactersInRange:range withString:string] intValue] * 2];
        return YES;
    }
}

-(BOOL)textFieldShouldClear:(UITextField *)textField{
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)];
    tapGestureRecognizer.delegate = self;
    [self.bgScrollView addGestureRecognizer:tapGestureRecognizer];
    
    [self.bgScrollView setContentOffset:CGPointMake(0,213) animated:YES];
    return YES;
}

- (IBAction)handleSingleTapGesture:(UITapGestureRecognizer*)sender{
    [mutipleTextField resignFirstResponder];
    if ([mutipleTextField.text length]==0) {
        mutipleTextField.text = @"1";
    }
    mutiLabel.text = [NSString stringWithFormat:@"%@倍", mutipleTextField.text];
    moneyLabel.text = [NSString stringWithFormat:@"%d彩豆", noteAmount * [mutipleTextField.text intValue] * 2];
    [self.bgScrollView removeGestureRecognizer:sender];
    [self.bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:buyButton]) {
        return NO;
    }
    
    return YES;
}

-(void)numberFromArray:(NSArray *)inNumberArray{
    if(!numberArray){
        numberArray = [NSMutableArray array];
    }
    [numberArray addObjectsFromArray:inNumberArray];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [numberArray count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 48.0;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return DELETE;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JddSelectFiveListItemCell *cell = [JddSelectFiveListItemCell getInstanceView];
    
    JddFc3dNumber *n7xNumber = [numberArray objectAtIndex:indexPath.row];
    NSMutableString *BallNumberString = [NSMutableString stringWithCapacity:([n7xNumber.BallArray count] + [n7xNumber.SecondBallArray count] + [n7xNumber.ThirdBallArray count] + [n7xNumber.FourthBallArray count] + [n7xNumber.FifthBallArray count] + [n7xNumber.SixthBallArray count] + [n7xNumber.SeventhBallArray count])];
    for (NSNumber *number in [JddCommonFunction sortArray: n7xNumber.BallArray]) {
        [BallNumberString appendFormat:@"%d ", [number intValue]];
    }
    [BallNumberString appendFormat:@"%@ ", @"| "];
    for (NSNumber *number in [JddCommonFunction sortArray: n7xNumber.SecondBallArray]) {
        [BallNumberString appendFormat:@"%d ", [number intValue]];
    }
    [BallNumberString appendFormat:@"%@ ", @"| "];
    for (NSNumber *number in [JddCommonFunction sortArray: n7xNumber.ThirdBallArray]) {
        [BallNumberString appendFormat:@"%d ", [number intValue]];
    }
    [BallNumberString appendFormat:@"%@ ", @"| "];
    for (NSNumber *number in [JddCommonFunction sortArray: n7xNumber.FourthBallArray]) {
        [BallNumberString appendFormat:@"%d ", [number intValue]];
    }
    [BallNumberString appendFormat:@"%@ ", @"| "];
    for (NSNumber *number in [JddCommonFunction sortArray: n7xNumber.FifthBallArray]) {
        [BallNumberString appendFormat:@"%d ", [number intValue]];
    }
    [BallNumberString appendFormat:@"%@ ", @"| "];
    for (NSNumber *number in [JddCommonFunction sortArray: n7xNumber.SixthBallArray]) {
        [BallNumberString appendFormat:@"%d ", [number intValue]];
    }
    [BallNumberString appendFormat:@"%@ ", @"| "];
    for (NSNumber *number in [JddCommonFunction sortArray: n7xNumber.SeventhBallArray]) {
        [BallNumberString appendFormat:@"%d ", [number intValue]];
    }
    cell.BallLabel.text = BallNumberString;
    cell.tag = indexPath.row;
    cell.delegate = self;
    return cell;
}

-(void)SelectFiveListItemCellDeleteButtonClicked:(NSNumber *)rowNumber{
    for (int i = [rowNumber intValue] + 1; i < [numberArray count]; ++i) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell *cell = [lotNumListTable cellForRowAtIndexPath:indexPath];
        cell.tag--;
    }
    [numberArray removeObjectAtIndex:[rowNumber intValue]];
    [lotNumListTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[rowNumber intValue] inSection:0]] withRowAnimation:YES];
    //cacualate count and money
    [self caculateCountMoney];
}

-(void)caculateCountMoney{
    noteAmount = 0;
    for (JddFc3dNumber *lotteryNum in numberArray) {
        noteAmount += [[lotteryNum BallArray] count]*[[lotteryNum SecondBallArray] count]*[[lotteryNum ThirdBallArray] count]*[[lotteryNum FourthBallArray] count]*[[lotteryNum FifthBallArray] count]*[[lotteryNum SixthBallArray] count]*[[lotteryNum SeventhBallArray] count];
    }
    countLabel.text = [NSString stringWithFormat:@"%d注", noteAmount];
    mutiLabel.text = [NSString stringWithFormat:@"%@倍", mutipleTextField.text];
    moneyLabel.text = [NSString stringWithFormat:@"%d彩豆", noteAmount * [mutipleTextField.text intValue] * 2];
}

-(void)destoryView{
    numberArray = [[NSMutableArray alloc] init];
    [lotNumListTable reloadData];
    [mutipleTextField resignFirstResponder];
    mutipleTextField.text = @"1";
    noteAmount = 0;
    countLabel.text = [NSString stringWithFormat:@"%d注", noteAmount];
    mutiLabel.text = [NSString stringWithFormat:@"%@倍", mutipleTextField.text];
    moneyLabel.text = [NSString stringWithFormat:@"%d彩豆", noteAmount * [mutipleTextField.text intValue] * 2];
}

- (IBAction)coBuyBtnClick:(id)sender {
    if([self checkValue]){
    JddLotteryIssue *ls = ((JddPickNum7xcViewController *)self.fromController).currentLotteryIssue;
    [FaQiHeMaiViewController sharedInstance].bs = [mutipleTextField.text intValue];
    [FaQiHeMaiViewController sharedInstance].lotID = LOTTERY_TYPE_ID_7XC;
    [FaQiHeMaiViewController sharedInstance].issueID = ls.code;
    [FaQiHeMaiViewController sharedInstance].issueName = ls.name;
    [FaQiHeMaiViewController sharedInstance].issueNameTitle = [NSString stringWithFormat:@"七星彩第%@期合买",ls.name];
    [FaQiHeMaiViewController sharedInstance].allMoney = noteAmount * [mutipleTextField.text intValue] * 2;
    [FaQiHeMaiViewController sharedInstance].lotteryNumber = [self lotteryNumberList];
    [[JddViewControllerManager sharedInstance].navigationController pushViewController:[FaQiHeMaiViewController sharedInstance] animated:YES];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([[alertView message] isEqualToString:@"确认购买？"]) {
        if (buttonIndex==0) {
            [self sureToBuy];
        }
    }else if ([[alertView message] isEqualToString:@"您还没有登录，请先登录"]) {
        if (buttonIndex == 0) {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN
                                                                 fromController:self
                                                                     withObject:nil
                                                                    withObject2:nil];
        }
    } else {
        if (buttonIndex==0) {
            [numberArray removeAllObjects];
            [lotNumListTable reloadData];
            noteAmount = 0;
            for (JddShuangSeQiuNumber *ssqNumber in numberArray) {
                if ([ssqNumber.redBallArray count] != 6 ||
                    [ssqNumber.blueBallArray count] != 1) {
                    noteAmount += [JddCommonFunction countShuangSeQiuTotalNumber:[ssqNumber.redBallArray count] blueBallAmount:[ssqNumber.blueBallArray count]];
                }
                else {
                    noteAmount++;
                }
            }
            mutipleTextField.text = @"1";
            countLabel.text = [NSString stringWithFormat:@"%d注", noteAmount];
            mutiLabel.text = [NSString stringWithFormat:@"%@倍", mutipleTextField.text];
            moneyLabel.text = [NSString stringWithFormat:@"%d彩豆", noteAmount * [mutipleTextField.text intValue] * 2];
        }
    }

}

- (void)sureToBuy{
    if ([self checkValue]) {
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    JddBuyLotteryOperation *operation2 = [[JddBuyLotteryOperation alloc] init];
    operation2.delegate = self;
    JddLotteryIssue *ls = ((JddPickNum7xcViewController*)self.fromController).currentLotteryIssue;
    operation2.lotteryTypeId = [NSNumber numberWithInt:3];
    operation2.issueId = [NSNumber numberWithInt:[ls.code intValue]];
    operation2.multiple = [NSNumber numberWithInt:[mutipleTextField.text intValue]];
    operation2.moneyAmount = [NSNumber numberWithFloat:noteAmount * [mutipleTextField.text intValue] * 2];
    operation2.lotteryNumber = [self lotteryNumberList];
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation2];
    }
}

-(NSMutableArray*)lotteryNumberList{
    NSMutableArray *paramNumberArray = [[NSMutableArray alloc] init];
    for (JddFc3dNumber *n7xNum in numberArray) {
        NSMutableString *lotString = [NSMutableString string];
        NSMutableDictionary *numDic = [[NSMutableDictionary alloc] init];
        int playid = LOTTERY_PLAY_METHOD__DS_QIXINGCAI;
        int i = [[n7xNum BallArray] count]*[[n7xNum SecondBallArray] count]*[[n7xNum ThirdBallArray] count]*[[n7xNum FourthBallArray] count]*[[n7xNum FifthBallArray] count]*[[n7xNum SixthBallArray] count]*[[n7xNum SeventhBallArray] count];
        if (i != 1) {
            playid = LOTTERY_PLAY_METHOD__FS_QIXINGCAI;
        }
        [numDic setObject:[NSNumber numberWithInt:playid] forKey:@"playid"];
        NSArray *ballArray = [NSArray arrayWithObjects:n7xNum.BallArray, n7xNum.SecondBallArray, n7xNum.ThirdBallArray, n7xNum.FourthBallArray, n7xNum.FifthBallArray, n7xNum.SixthBallArray, n7xNum.SeventhBallArray, nil];
        [JddCommonFunction paramsWithQXCorPWArray:ballArray AndString:lotString];
        [numDic setObject:lotString forKey:@"number"];
        [paramNumberArray addObject:numDic];
    }
     return paramNumberArray;
}

-(void)BuyLotteryOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if(result)
    {
        NSDictionary *ReDic = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
        if([[ReDic objectForKey:@"Code"] intValue] == 0)
        {
            // modify by rainy  修改投注使用接口不经过web
            NSString * fanganhao = [ReDic objectForKey:@"Data"];
            JddLotteryIssue *ls = ((JddPickNum7xcViewController *)self.fromController).currentLotteryIssue;
            alert1 = [JddAlertView getInstanceView];
            alert1.lssueString = fanganhao;
            alert1.moneylable = moneyLabel.text;
            [alert1 alertBuyMessage:[NSString stringWithFormat:@"七星彩%@期",ls.name]];
//            NSString*checkUrlString = [NSString stringWithFormat:@"%@?ck=%@",BASE_SERVER_IOS_BUY_LOTTERY_URL,[ReDic objectForKey:@"Data"]];
//            NSURL *checkUrl = [NSURL URLWithString:checkUrlString];
//            [[UIApplication sharedApplication] openURL:checkUrl];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"购彩失败"                                                  message:[ReDic objectForKey:@"Data"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil,nil ];
            [alert show];
        }
//        [JddCommonFunction updateBuyLotteryListWithLotteryId:LOTTERY_TYPE_ID_7XC];
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    agreeLotteryForFooterView = [JddAgreeLotteryForFooterView getInstanceView];
    agreeLotteryForFooterView.fromViewController = self;
    lotNumListTable.tableFooterView = agreeLotteryForFooterView;
   // [self.navigationItem setTitle:PAGE_7X_PICK_NUMBER_LIST];
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:PAGE_7X_PICK_NUMBER_LIST];
        customLab.textAlignment = NSTextAlignmentCenter;

        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
        
//        //self.navigationItem.hidesBackButton = YES;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"7XC-detail"];

    [lotNumListTable reloadData];
    //caculate count and money
    [self caculateCountMoney];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [MobClick endLogPageView:@"7XC-detail"];
    
    if ([mutipleTextField.text length]==0) {
        mutipleTextField.text = @"1";
    }
    [mutipleTextField resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setBgScrollView:nil];
    [self setLotNumListTable:nil];
    [self setMutipleTextField:nil];
    [self setCountLabel:nil];
    [self setMutiLabel:nil];
    [self setMoneyLabel:nil];
    [self setBuyButton:nil];
    [super viewDidUnload];
}
- (IBAction)continueBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)continueRandomBtn:(id)sender {
    UIButton* btn = sender;
    [btn setEnabled:NO];
    JddFc3dNumber *num = [[JddFc3dNumber alloc] init];
    [num clear];
    [num addBallNumber:arc4random()%10];
    [num add2BallNumber:arc4random()%10];
    [num add3BallNumber:arc4random()%10];
    [num add4BallNumber:arc4random()%10];
    [num add5BallNumber:arc4random()%10];
    [num add6BallNumber:arc4random()%10];
    [num add7BallNumber:arc4random()%10];
    [numberArray addObject:num];
    [lotNumListTable reloadData];
    [self caculateCountMoney];
    [btn setEnabled:YES];
}

- (IBAction)reduceBtn:(id)sender {
    NSInteger multiple = [mutipleTextField.text intValue];
    if (multiple-- < 2) {
        mutipleTextField.text = @"1";
        return;
    }
    mutipleTextField.text = [NSString stringWithFormat:@"%d", multiple];
    mutiLabel.text =[NSString stringWithFormat:@"%d倍", multiple];
    moneyLabel.text = [NSString stringWithFormat:@"%d彩豆", noteAmount * multiple * 2];

}

- (IBAction)addBtn:(id)sender {
    NSInteger multiple = [mutipleTextField.text intValue];
    if (multiple>998) {
        return;
    }
    mutipleTextField.text = [NSString stringWithFormat:@"%d", ++multiple];
    mutiLabel.text =[NSString stringWithFormat:@"%d倍", multiple];
    moneyLabel.text = [NSString stringWithFormat:@"%d彩豆", noteAmount * multiple * 2];

}

- (IBAction)clearBtn:(id)sender {
    if ([lotNumListTable numberOfRowsInSection:0]>0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"确认清空列表？"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:@"取消",nil ];
        [alert show];
        
    }
}

- (IBAction)buyBtn:(id)sender {
    int multiple = [mutipleTextField.text intValue];
    if (![JddCommonFunction isLogin]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"您还没有登录，请先登录"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:@"取消",nil ];
        [alert show];
    } else {
        if (!agreeLotteryForFooterView.checkBoxBtn.selected) {
            [JddCommonFunction messageBoxWithMessage:BUY_NOT_READ];
        }
        else if ([numberArray count]==0) {
            [JddCommonFunction messageBoxWithMessage:BALL_COUNT_NULL];
        }else{
            if (multiple == 0) {
                [JddCommonFunction messageBoxWithMessage:MULTIPLE_Tip];
            }
            else {
                [self sureToBuy];
                /*
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
                                                            message:@"确认购买？"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:@"取消",nil ];
            [alert show];*/
                }
        }
    }
}

- (IBAction)textFiledDidEnd:(id)sender {
    [mutipleTextField resignFirstResponder];
}

-(BOOL)checkValue{
    if ([mutipleTextField.text intValue]>999) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"倍数不能大于999"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        mutipleTextField.text =  @"999";
        return NO;
    }else if ((noteAmount * [mutipleTextField.text intValue] * 2) > 2000000 ){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                        message:@"单个方案的总金额必须在2彩豆至2000000彩豆之间"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil,nil ];
        [alert show];
        return NO;
    }
    return YES;
}


@end
